package com.example.lastwork2.cart;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.example.lastwork2.MainActivity;
import com.example.lastwork2.R;
import com.example.lastwork2.adapter.CartAdapter;
import com.example.lastwork2.adapter.RecAdapter;
import com.example.lastwork2.fragments.detail.ShopDetailActivity;
import com.example.lastwork2.model.Shop;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

public class CartActivity extends AppCompatActivity {

    //控件对象
    private ListView cartList;
    public static TextView sumPriceKongJian;
    public static Button buy;

    public static Double sumPrice;

    //用于从数据库中接收当前用户的购物车信息    去重之后的
    private List<Shop> cartShop = new ArrayList<>();
    //用于从数据库接收当前用户对应商品的数量  curnum
    private List<Integer> curnum = new ArrayList<>();
    //用于存储购物车的所有商品信息，不去重   结算是创建新订单时使用
    private List<Shop> cartShop1 ;



//    //用于存储购物车的所有商品信息，不去重   结算是创建新订单时使用
//    private List<Shop> cartShop1 ;

    //购物车适配器对象
    private CartAdapter cartAdapter;

    //用于实现延迟刷新
    private Handler handler;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);

        //绑定控件
        getViews();

        //获取数据  从数据库中获取数据 将获取的信息放入cartShop局部变量  并且获取商品对应的数量放到curnum局部变量中
        //必须在这个线程完毕之后才能往下执行
        getCartShopFromServer();



    }


    //接收数据库中本用户的购物车信息
    private void getCartShopFromServer() {
        String url1 = "http://10.0.2.2:8080/bigwork/cart";
        new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    URL url = new URL(url1+"?userId="+ MainActivity.userId);
                    URLConnection urlConnection = url.openConnection();
                    //接收服务器发来的数据
                    InputStream inputStream = urlConnection.getInputStream();
                    //创建字符流读取数据
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
                    String str = bufferedReader.readLine();
                    //服务器发送json数据成功
                    System.out.println(str);
                    //关闭流
                    bufferedReader.close();
                    inputStream.close();

                    //分割数据
                    String strShop = str.split("]",2)[0] + "]";
                    String strCount = str.split("]",2)[1];
                    System.out.println(strShop);
                    System.out.println(strCount);//[1,1,2,5] 这种



                    //解析数据
                    Gson gson = new Gson();
                    cartShop = gson.fromJson(strShop,new TypeToken<List<Shop>>(){}.getType());
//                    curnum = gson.fromJson(strShop,new TypeToken<List<Object>>(){}.getType());
//                    接着分割字符串
                    //先取出两边的【】
                    String a = strCount.replace("[","");
                    String b = a.replace("]","");

                    System.out.println(b);
                    for(int i=0;i<cartShop.size();i++){
                        String c = b.split(",",cartShop.size())[i];
                        int d = Integer.parseInt(c);
                        curnum.add(d);
                    }

                    ShopDetailActivity.cartShop = cartShop;
                    ShopDetailActivity.curnum = curnum;




                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }


                //在子线程里面更新主线程
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //加载activity时就计算商品总价格
                        //获取商品总金额
                        CartActivity.sumPrice=0.0;
                        for(int i = 0;i<curnum.size();i++){
                            //获取i位置的商品数量
                            int counti = curnum.get(i);
                            //获取i位置的商品价格
                            double pricei = Double.parseDouble(String.valueOf(ShopDetailActivity.cartShop.get(i).getPrice()));
                            //计算总金额
                            sumPrice = sumPrice + (counti * pricei);
                            sumPrice =(double) Math.round(sumPrice*100)/100;
                        }
                        sumPriceKongJian.setText(sumPrice+"");








                        //将数据利用适配器显示到对应控件中
                        cartAdapter = new CartAdapter(
                                CartActivity.this,
                                R.layout.activity_cart_item,
                                cartShop
                        );
                        cartList.setAdapter(cartAdapter);

                    }
                });




            }
        }).start();





    }

    private void flush() {
        finish();
        Intent intent = new Intent();
        intent.setClass(CartActivity.this,CartActivity.class);
        startActivity(intent);

    }


    private void sendToServer(List<Shop> cartShop1) {

        String url1 = "http://10.0.2.2:8080/bigwork/order";
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Gson gson = new Gson();
                    String jsonData = gson.toJson(cartShop1);

                    HttpURLConnection connection = (HttpURLConnection) new URL(url1).openConnection();
                    connection.setRequestMethod("POST");
                    //向服务器发送json数据
                    OutputStream os = connection.getOutputStream();
                    os.write(jsonData.getBytes());
                    os.flush();

                    String jsonUserId = gson.toJson(MainActivity.userId);
                    os.write(jsonUserId.getBytes());
                    os.flush();

                    os.close();




                    //接受服务器传来的数据
                    InputStream inputStream = connection.getInputStream();
                    //创建字符流读取数据
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
                    String str = bufferedReader.readLine();

                    //服务器发送json数据成功
                    System.out.println(str);

                    //关闭流
                    bufferedReader.close();
                    inputStream.close();




                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }
        }).start();


    }

    private void sendCartToServer(List<Shop> cartShop, List<Integer> curnum) {
        String url1 = "http://10.0.2.2:8080/bigwork/cart";

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Gson gson = new Gson();

                    HttpURLConnection connection = (HttpURLConnection) new URL(url1).openConnection();
                    connection.setRequestMethod("POST");
                    //向服务器发送json数据
                    OutputStream os = connection.getOutputStream();
                    //发送cartShop数据
                    String jsonData = gson.toJson(cartShop);
                    os.write(jsonData.getBytes());
                    os.flush();
                    //发送curnum数据
                    String jsonCurnum = gson.toJson(curnum);
                    os.write(jsonCurnum.getBytes());
                    os.flush();
                    //发送userId
                    String jsonUserId = gson.toJson(MainActivity.userId);
                    os.write(jsonUserId.getBytes());
                    os.flush();
                    os.close();

                    //接受服务器传来的数据
                    InputStream inputStream = connection.getInputStream();
                    //创建字符流读取数据
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
                    String str = bufferedReader.readLine();

                    //服务器发送json数据成功
                    System.out.println(str);

                    //关闭流
                    bufferedReader.close();
                    inputStream.close();




                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }




            }
        }).start();



    }


    private void getViews() {
        cartList = findViewById(R.id.cart_list);
        sumPriceKongJian = findViewById(R.id.sum_price);
        buy = findViewById(R.id.settle_shops);

    }

}